package com._51doit.day01.xingge例子

/**
 * 方法跟函数的区别
 *
 * 函数和方法都可以封装运算逻辑
 *
 * 1.定义方法用def关键字
 * 2.函数本质就是引用类型,可以作为参数传入打方法中，也可以作为方法的返回值
 *
 */
object MethodAndFunctionDemo {

  def m1(x: Int): Double = x * 10.0


  def main(args: Array[String]): Unit = {

    //匿名函数，通常直接传入到方法中


    val arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)

    arr.flatMap()

    val res1: Array[Int] = arr.map(_ * 10)

    arr.reduce((a, b) => a + b)

    val filtered: Array[Int] = arr.filter(_ % 2 == 0)


    //val f: Int => Int = (x: Int) => x * 10

    //filtered.map(f)

    val f2 = (x: Int, y: Double) => (y, x)

    val f22: (Int, Double) => (Double, Int) = (x: Int, y: Double) => (y, x)

    f22.apply(3, 5);

    val f222: (Int, Double) => (Double, Int) = (x, y) => (y, x)

    val f0 = () => println(666)
    val f00: () => Unit = () => println(666)


    //函数真正的定义方式
    //函数的类型本质上是Function1[Int, Int]，等价于(Int) => Int
    val f5: Function1[Int, Int] = (x: Int) => x * 10
    val f6: (Int) => Int = (x: Int) => x * 10


    //val f7 = (v1: Int) => v1 * 10
    val f7: Function1[Int, Int] = new Function1[Int, Int] {
      override def apply(v1: Int): Int = v1 * 10
    }

    val r = f7(10) //val r = f7.apply(10)

    println(r)


    //函数本质就是引用类型，就相当于在内存中new出来的一个实例
    val f8 = new Function2[Int, Double, (Double, Int)] {
      override def apply(v1: Int, v2: Double): (Double, Int) = (v2, v1)
    }

    f8.apply(5, 6.6)


    //call by name
    arr.map(m1 _)

  }




}
